<?php
/**
 * 消息控制器
 */

namespace app\api\controller;

use app\api\exception\ApiServiceException;
use app\api\service\MessageService;
use app\common\validate\MessageValidate;
use hg\apidoc\annotation as Apidoc;
use think\response\Json;

/**
 * @Apidoc\Title("消息")
 * @Apidoc\Group("index")
 */
class MessageController extends ApiBaseController {
	/**
	 * @Apidoc\Title("列表")
	 * @Apidoc\Desc("列表")
	 * @Apidoc\Method("GET")
	 * @Apidoc\Url("/api/message/index")
	 * @Apidoc\Returned("data",        type="int",                 desc="desc")
	 */
	public function index(MessageService $service): Json {
		try {
			$data = $service->getList($this->param, $this->page, $this->limit);
			$result = [
				'message' => $data,
			];

			return api_success($result);
		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}

	/**
	 * 添加
	 * @param MessageValidate $validate
	 * @param MessageService $service
	 * @return Json
	 */
	public function add(MessageValidate $validate, MessageService $service): Json {
		$check = $validate->scene('api_add')->check($this->param);
		if (!$check) {
			return api_error($validate->getError());
		}

		$result = $service->createData($this->param);

		return $result ? api_success() : api_error();
	}

	/**
	 * 详情
	 * @param MessageValidate $validate
	 * @param MessageService $service
	 * @return Json
	 */
	public function info(MessageValidate $validate, MessageService $service): Json {
		$check = $validate->scene('api_info')->check($this->param);
		if (!$check) {
			return api_error($validate->getError());
		}

		try {

			$result = $service->getDataInfo($this->id);
			return api_success([
				'message' => $result,
			]);

		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}

	/**
	 * 修改
	 * @param MessageService $service
	 * @param MessageValidate $validate
	 * @return Json
	 */
	public function edit(MessageService $service, MessageValidate $validate): Json {
		$check = $validate->scene('api_edit')->check($this->param);
		if (!$check) {
			return api_error($validate->getError());
		}

		try {
			$service->updateData($this->id, $this->param);
			return api_success();
		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}

	/**
	 * 删除
	 * @param MessageService $service
	 * @param MessageValidate $validate
	 * @return Json
	 */
	public function del(MessageService $service, MessageValidate $validate): Json {
		$check = $validate->scene('api_del')->check($this->param);
		if (!$check) {
			return api_error($validate->getError());
		}

		try {
			$service->deleteData($this->id);
			return api_success();
		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}

}
